const http = require('http')
const url = require('url')
const webhookHandler = require('./webhookHandler')
const now = require('./now')
const port = 3000

const requestHandler = function (request, response) {
  logRequest(request)

  let data = ''
  let path = url.parse(request.url).pathname
  path = path.substring(1)

  request.on('data', function (chunk) {
    data += chunk;
  })

  request.on('end', function () {
    logData(data)
    try {
      data = JSON.parse(data)
    } catch (err) {
      response.writeHead(400)
      response.end('请求消息体的JSON格式异常！')
    }
    let body = webhookHandler(path, data, request, response)
    response.writeHead(body[0])
    response.end(body[1])
  })
}

const start = function () {
  http.createServer(requestHandler).listen(port, (err) => {
    if (err) {
      return console.log('something bad happened', err)
    } else {
      console.log(`server is listening on ${port}`)
    }
  })
}

function logRequest(request) {
  console.log(`### handle new request at ${now()} ###`)
  // console.log('request: ', request)
}

function logData(data) {
  // console.log('request data: ', data)
}

exports.start = start
